<template>
  <Dialog
    :title="dialogTitle"
    v-model="dialogVisible"
    :max-height="maxHeight"
    :width="width"
    append-to-body
    style="padding-bottom: 0px !important"
  >
    <el-container>
      <el-aside class="aside">
        <el-scrollbar :max-height="maxHeight" class="pr-20px">
          <div
            class="payment-item"
            v-for="(item, index) in state.payMethods"
            @click="selectPayMent(index)"
            :key="index"
            :class="{ 'payment-item-active': nowPaymentIndex == index || item.payStatus }"
          >
            <!-- <el-image :src="item.icon" class="icon ml-10px" /> -->
            <el-text class="custom-text-18 ml-10px!" truncated> {{ item.classiName }}</el-text>
            <div class="virtual_san" v-if="item.payStatus"></div>
            <div class="virtual_dui custom-text-18" v-if="item.payStatus">✓</div>
          </div>
        </el-scrollbar>
      </el-aside>
      <el-main class="main">
        <el-row class="payment-info" v-if="nowPayment.classify == 'updatePrice'">
          <el-col :xs="8" :sm="8" :md="8" :lg="8" :xl="8">
            <div class="text-center">
              <div class="custom-text-24 c-[var(--el-color-primary)]!"
                >￥{{ fenToYuan(prcieCount) }}</div
              >
              <div class="custom-text-18">零售总价</div>
            </div>
          </el-col>
          <el-col :xs="8" :sm="8" :md="8" :lg="8" :xl="8">
            <div class="text-center">
              <div class="custom-text-24 c-[var(--el-color-primary)]!"
                >￥{{ fenToYuan(discountPrice) }}</div
              >
              <div class="custom-text-18">总计优惠</div>
            </div>
          </el-col>
          <el-col :xs="8" :sm="8" :md="8" :lg="8" :xl="8">
            <div class="text-center">
              <div class="custom-text-24 c-[var(--el-color-primary)]!"
                >￥{{ fenToYuan(payPrice) }}</div
              >
              <div class="custom-text-18">实售总价</div>
            </div>
          </el-col>
        </el-row>
        <el-row class="payment-info" v-else-if="nowPayment.classify == 'debtPrice'">
          <el-col :xs="12" :sm="12" :md="12" :lg="12" :xl="12">
            <div class="text-center">
              <div class="custom-text-24 c-[var(--el-color-primary)]!"
                >￥{{ fenToYuan(selectedSku.realPrice) }}</div
              >
              <div class="custom-text-18">实售总价</div>
            </div>
          </el-col>
          <el-col :xs="12" :sm="12" :md="12" :lg="12" :xl="12">
            <div class="text-center">
              <div class="custom-text-24 c-[var(--el-color-primary)]!"
                >￥{{ fenToYuan(formData.arrearsPrice) }}</div
              >
              <div class="custom-text-18">欠款金额</div>
            </div>
          </el-col>
        </el-row>
        <el-row class="payment-info" v-else>
          <el-col :xs="8" :sm="8" :md="8" :lg="8" :xl="8">
            <div class="text-center">
              <div class="custom-text-24 c-[var(--el-color-primary)]!"
                >￥{{ fenToYuan(selectedSku.price) }}</div
              >
              <div class="custom-text-18">零售单价</div>
            </div>
          </el-col>
          <el-col :xs="8" :sm="8" :md="8" :lg="8" :xl="8">
            <div class="text-center">
              <div class="custom-text-24 c-[var(--el-color-primary)]!"
                >￥{{ fenToYuan(selectedSku.singlePrice) }}</div
              >
              <div class="custom-text-18">实售单价</div>
            </div>
          </el-col>
          <el-col :xs="8" :sm="8" :md="8" :lg="8" :xl="8">
            <div class="text-center">
              <div class="custom-text-24 c-[var(--el-color-primary)]!"
                >￥{{ fenToYuan(selectedSku.realPrice) }}</div
              >
              <div class="custom-text-18">实售总价</div>
            </div>
          </el-col>
        </el-row>
        <template v-if="JSON.stringify(nowPayment) != '{}'">
          <div class="payment-operation">
            <div class="flex-1">
              <div class="mt-10px">
                <el-input
                  v-if="nowPayment.classify == 'debtPrice'"
                  v-model="nowPayment.usePayBalance"
                  class="payment-input custom-text-44"
                  @blur="testArrears"
                  ref="inputRef"
                  :formatter="(value: any) => verifyNumberIntegerAndFloat(value)"
                >
                  <template #prepend>
                    <div class="flex items-center">
                      <el-image :src="collection" class="collection-icon" />
                      <span class="custom-text-22 ml-5px">欠款金额</span>
                    </div>
                  </template>
                </el-input>
                <el-input
                  v-if="nowPayment.classify == 'updatePrice'"
                  v-model="nowPayment.usePayBalance"
                  class="payment-input custom-text-28"
                  @blur="testDiscount"
                  @input="countPayPrice"
                  :formatter="handleFormatterDiscountPrice"
                  :placeholder="
                    formData.distType == 0
                      ? '请输入优惠后商品总价'
                      : formData.distType == 1
                        ? '请输入商品折扣(1-100)'
                        : ''
                  "
                >
                  <template #prepend>
                    <div class="flex items-center p-x-10px">
                      <!-- <el-image :src="collection" class="collection-icon" /> -->
                      <el-select
                        v-model="formData.distType"
                        size="large"
                        class="w-120px! h-60px! select-box"
                      >
                        <el-option
                          v-for="item in discountTypeOptions"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                        >
                          <span class="custom-text-18!">{{ item.label }}</span></el-option
                        >
                      </el-select>
                    </div>
                  </template>
                  <template #append>
                    <span class="custom-text-22">
                      {{ formData.distType == 0 ? '元' : formData.distType == 1 ? '折' : '' }}
                    </span>
                  </template>
                </el-input>
              </div>
              <div class="flex justify-between w-100% items-center h-30px! mt-10px">
                <div
                  class="custom-text-20"
                  style="color: #707070"
                  v-if="nowPayment.classify == 'updatePrice'"
                >
                  <span v-if="!state.isHideLowePrice">
                    最低限价:
                    {{ fenToYuan(selectedSku.lowerPrice) }}
                  </span>
                  <span v-if="state.isHideLowePrice"> 最低限价****** </span>
                  <Icon
                    :icon="state.isHideLowePrice ? 'ep:view' : 'ep:hide'"
                    class="ml-10px"
                    @click="
                      () => {
                        state.isHideLowePrice = !state.isHideLowePrice
                      }
                    "
                  />
                </div>
                <div v-else> &nbsp;</div>
                <div class="flex">
                  <el-text type="primary" class="custom-text-18 mr-5px!" @click="onHandleCancel">
                    取消{{ nowPayment.classify == 'updatePrice' ? '优惠' : '欠款' }}
                  </el-text>
                </div>
              </div>
            </div>
            <div class="flex items-center mt-10px justify-center">
              <DigitKeyboard
                ref="DigitKeyboardRef"
                @on-change="onInputChange"
                @on-confirm="onConfirm"
                :disabled="nowPayment.payStatus || formLoading"
                :input="nowPayment.usePayBalance"
              />
            </div>
          </div>
        </template>

        <template v-if="JSON.stringify(nowPayment) == '{}'">
          <div class="payment-operation flex-1 justify-center!">
            <el-result title="请左侧选择方式进行支付" class="h-450px">
              <template #icon>
                <el-image :src="defaultPaymentImg" />
              </template>
            </el-result>
          </div>
        </template>
      </el-main>
    </el-container>

    <template #footer v-if="slots.footer">
      <slot name="footer"></slot>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
// 储值卡弹窗
import { defineAsyncComponent, ref, useSlots } from 'vue'
import collection from '@/assets/svgs/collection.svg'
import defaultPaymentImg from '@/assets/svgs/pay/icon/payment.png'

import { fenToYuan, yuanToFen } from '@/utils'

const DigitKeyboard = defineAsyncComponent(() => import('./digitKeyBoard.vue'))
const slots = useSlots()
import { propTypes } from '@/utils/propTypes'
const props = defineProps({
  orderInfo: propTypes.object, //订单信息
  paymentMap: propTypes.array
})
// 检测支付环境
const state = reactive({
  orderInfo: computed(() => {
    return props.orderInfo
  }), // 支付单信息
  payMethods: ref([
    {
      classiName: '商品优惠',
      classify: 'updatePrice',
      payStatus: false
    },
    {
      classiName: '商品欠款',
      classify: 'debtPrice',
      payStatus: false
    }
  ]), // 可选的支付方式
  payment: '', // 选中的支付方式
  payOrderList: [] as any, //当前支付方式的支付流水号
  activeName: '', //当前选中的支付方式
  isHideLowePrice: true
})
const selectedSku = ref({} as any)
const formData = ref({
  id: undefined, // 订单编号
  arrearsPrice: '' as any, // 欠款金额
  distType: 0, //优惠类型
  distPrice: '' as any, //优惠值
  payPrice: '' as any // 调价后应付金额(总)
})
const discountTypeOptions = computed(() => {
  return [
    {
      label: '总价',
      value: 0
    },
    {
      label: '折扣',
      value: 1
    }
  ]
})
const payPrice = computed(() => {
  if (formData.value.distPrice > 0) {
    return formData.value.payPrice
  } else {
    return selectedSku.value.realPrice
  }
}) //前端计算的实售总价
const prcieCount = computed(() => {
  return selectedSku.value.price * selectedSku.value.count
}) //零售总价
const discountPrice = computed(() => {
  let discount = prcieCount.value - payPrice.value
  return discount > 0 ? discount : 0
}) //优惠金额
const DigitKeyboardRef = ref()
const onInputChange = (input: any) => {
  nowPayment.value.usePayBalance = input
} //输入发生变化时
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('商品修改:独立优惠丨独立欠款') // 弹窗的标题
const width = ref('715px') //宽度
const maxHeight = ref('545px')
// 选择支付方式

const nowPayment = ref<any>({})
const nowPaymentIndex = ref<any>() //当前支付方式的下标
const inputRef = ref()
const selectPayMent = (index: any) => {
  let item = state.payMethods[index]
  if (item.classify == 'debtPrice' && selectedSku.value.isArrears) {
    message.error('该商品不允许欠款')
    return
  }
  // if (
  //   item.classify == 'updatePrice' &&
  //   selectedSku.value.lowerPrice == selectedSku.value.realPrice
  // ) {
  //   message.error('该商品不允许优惠')
  //   return
  // }
  nowPaymentIndex.value = index
  nowPayment.value = item
  if (nowPayment.value.classify == 'debtPrice') {
    nowPayment.value.usePayBalance = fenToYuan(formData.value.arrearsPrice)
  } else {
    if (formData.value.distType == 0) {
      nowPayment.value.usePayBalance = fenToYuan(formData.value.distPrice)
    }
    if (formData.value.distType == 1) {
      nowPayment.value.usePayBalance = formData.value.distPrice
    }
    countPayPrice()
  }
  // setKeyBoardLayout()
}

/** 打开弹窗 */

const open = async (row: any) => {
  resetForm()

  selectedSku.value = row
  formData.value.id = row.cartId!
  formData.value.arrearsPrice = Number(row.arrearsPrice!)
  formData.value.distType = row.distType
  // 先根据下标取
  if (row.arrearsPrice > 0) {
    state.payMethods[1].payStatus = true
  } else {
    state.payMethods[1].payStatus = false
  }
  if (row.distPrice > 0) {
    state.payMethods[0].payStatus = true
  } else {
    state.payMethods[0].payStatus = false
  }

  // if (formData.value.distType == 0) {
  //   formData.value.distPrice = row.distPrice ? fenToYuan(row.distPrice!) : ''
  // }
  // if (formData.value.distType == 1) {
  //   formData.value.distPrice = row.distPrice ? row.distPrice!.toString() : ''
  // }
  dialogVisible.value = true

  // await setNowPayment()
}
/** 优惠金额 */
/** 处理优惠输入限制 */
const handleFormatterDiscountPrice = (value: string) => {
  if (formData.value.distType == 0) {
    // 如果是优惠总价
    return verifyNumberIntegerAndFloat(value)
  } else if (formData.value.distType == 1) {
    // 如果是折扣 输入0到100的正整数
    return verifyNumberPercentage(value)
  }
}
const countPayPrice = () => {
  console.log(nowPayment.value.usePayBalance)
  if (formData.value.distType == 0) {
    formData.value.distPrice = yuanToFen(nowPayment.value.usePayBalance)

    formData.value.payPrice = formData.value.distPrice
  } else if (formData.value.distType == 1) {
    formData.value.distPrice = nowPayment.value.usePayBalance

    formData.value.payPrice =
      Number(selectedSku.value.realPrice || 0) * (Number(formData.value.distPrice) / 100)
  } else {
    return 0
  }
}
/** 校验折扣 */

const testDiscount = () => {
  if (nowPayment.value.usePayBalance) {
    console.log('计算')
    console.log(selectedSku.value.lowerPrice)
    console.log(formData.value.payPrice)

    countPayPrice()

    // 判断优惠价 是否低于最低价

    if (Number(selectedSku.value.lowerPrice) > Number(formData.value.payPrice)) {
      message.error('优惠价不得低于最低限价')
      return false
    } else {
      return true
    }
  } else {
    return false
  }
}
/** 校验欠款 */
const testArrears = () => {
  if (nowPayment.value.usePayBalance) {
    // 判断优惠价 是否低于最低价
    formData.value.arrearsPrice = yuanToFen(nowPayment.value.usePayBalance)
    if (Number(formData.value.arrearsPrice) > Number(selectedSku.value.realPrice)) {
      message.error('欠款金额不得低于实售总价')
      return false
    } else {
      return true
    }
  } else {
    return false
  }
}

const close = async () => {
  dialogVisible.value = false
  nowPayment.value.usePayBalance = ''
  // resetForm()
}
const onHandleCancel = () => {
  if (nowPayment.value.classify == 'debtPrice') {
    formData.value.arrearsPrice = 0
    submitDebtPrice()
  }
  if (nowPayment.value.classify == 'updatePrice') {
    formData.value.distPrice = 0
    formData.value.distType = 0
    submitUpdatePrice()
  }
}

defineExpose({ open, close }) // 提供 open 方法，用于打开弹窗

const message = useMessage() // 消息弹窗
import { verifyNumberIntegerAndFloat, verifyNumberPercentage } from '@/utils/formatter'
import { cloneDeep } from 'lodash-es'
import { useShopCartStoreWithOut } from '@/store/modules/shop/cart'
/** 购物车信息 */

const onConfirm = () => {
  if (nowPayment.value.classify == 'debtPrice') {
    const testArrearsStatus = testArrears()
    if (testArrearsStatus) {
      submitDebtPrice()
    } else {
    }
  }
  if (nowPayment.value.classify == 'updatePrice') {
    const testUpdatePriceStatus = testDiscount()
    if (testUpdatePriceStatus) {
      submitUpdatePrice()
    } else {
    }
  }
} //确认当前支付方式
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const shopCartStore = useShopCartStoreWithOut()
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调

const submitDebtPrice = async () => {
  // 提交请求
  formLoading.value = true
  try {
    const data = cloneDeep(unref(formData))

    await shopCartStore.updateCart({
      id: data.id,
      count: selectedSku.value.count,
      arrearsPrice: data.arrearsPrice
    })
    dialogVisible.value = false
    message.success('设置成功')

    // 发送操作成功的事件
    emit('success', true)
  } finally {
    formLoading.value = false
  }
}
const { t } = useI18n() // 国际化

const submitUpdatePrice = async () => {
  // 提交请求
  formLoading.value = true
  try {
    const data = cloneDeep(unref(formData))

    await shopCartStore.updateCart({
      id: data.id,
      distType: data.distType,
      count: selectedSku.value.count,
      payPrice: data.payPrice,
      distPrice: data.distPrice
    })
    message.success(t('common.updateSuccess'))

    // 发送操作成功的事件
    emit('success', true)
    close()
  } finally {
    formLoading.value = false
  }
}
const resetForm = () => {
  formData.value = {
    id: undefined, // 订单编号
    distType: 0,
    arrearsPrice: '',
    distPrice: '', //优惠值
    payPrice: '' // 调价后应付金额(总)
  }
}
</script>
<style lang="scss" scoped>
:deep(.el-input.is-disabled .el-input__wrapper) {
  background: transparent !important;
}
.select-box {
  font-size: 24px;

  :deep(.el-select__wrapper) {
    box-shadow: none !important;
    height: 60px !important;
  }
  :deep(.el-select__placeholder) {
    color: #fff;
    font-size: 24px;
  }
  :deep(.el-select__caret) {
    color: #fff;
    font-size: 24px;
  }
}
.aside {
  width: 210px;
}

.main {
  width: 470px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

:deep(.el-main) {
  --el-main-padding: 0px !important;
  width: 470px;
}

// .payment-item {
//   width: 190px;
//   height: 70px;
//   background: url('@/assets/imgs/payCashier/paymentBg.png') center no-repeat;
//   background-size: 100% 100%;
//   cursor: pointer;
//   display: flex;
//   align-items: center;
//   margin-bottom: 10px;
//   color: #fff;
//   .icon {
//     width: 24px;
//     height: 24px;
//   }

//   .virtual_san {
//     display: none;
//   }

//   .virtual_dui {
//     display: none;
//   }

//   &-active {
//     background: url('@/assets/imgs/payCashier/paymentActive.png') center no-repeat;
//     background-size: 100% 100%;
//     position: relative;

//     .virtual_san {
//       display: block;
//       position: absolute;
//       bottom: 0;
//       right: 0;
//       width: 0;
//       height: 0;
//       border-bottom: 35px solid var(--el-color-primary);
//       border-left: 35px solid transparent;
//       border-bottom-right-radius: 5px;
//     }

//     .virtual_dui {
//       display: block;

//       position: absolute;
//       bottom: -2px;
//       right: 5px;
//       color: #fff;
//       font-family: system-ui;
//     }
//   }
// }
// .dark .payment-item {
//   width: 190px;
//   height: 70px;
//   background: url('@/assets/imgs/payCashier/paymentBg.png') center no-repeat;
//   background-size: 100% 100%;
//   cursor: pointer;
//   display: flex;
//   align-items: center;
//   margin-bottom: 10px;
//   color: #fff;
//   .icon {
//     width: 24px;
//     height: 24px;
//   }

//   .virtual_san {
//     display: none;
//   }

//   .virtual_dui {
//     display: none;
//   }

//   &-active {
//     background: url('@/assets/imgs/payCashier/paymentActive.png') center no-repeat;
//     background-size: 100% 100%;
//     position: relative;

//     .virtual_san {
//       display: block;
//       position: absolute;
//       bottom: 0;
//       right: 0;
//       width: 0;
//       height: 0;
//       border-bottom: 35px solid var(--el-color-primary);
//       border-left: 35px solid transparent;
//       border-bottom-right-radius: 5px;
//     }

//     .virtual_dui {
//       display: block;

//       position: absolute;
//       bottom: -2px;
//       right: 5px;
//       color: #fff;
//       font-family: system-ui;
//     }
//   }
// }

// .payment-info {
//   width: 470px;
//   height: 85px;
//   display: flex;
//   flex-direction: row;
//   justify-content: space-between;
//   align-items: center;
//   background-color: var(--app-content-bg-color) !important;
//   border-radius: 5px;

//   &-item {
//     width: 117.5px;
//     text-align: center;
//   }
// }
// .dark .payment-info {
//   width: 470px;
//   height: 85px;
//   display: flex;
//   flex-direction: row;
//   justify-content: space-between;
//   align-items: center;
//   background-color: var(--el-bg-color-overlay) !important;
//   border-radius: 5px;

//   &-item {
//     width: 117.5px;
//     text-align: center;
//   }
// }
// .payment-operation {
//   flex: 1;
//   display: flex;
//   flex-direction: column;
//   justify-content: space-between;
// }
.payment-input {
  width: 470px;

  height: 60px;

  :deep(.el-input-group__prepend) {
    background: var(--el-color-primary);
    color: #fff;
    padding: 0 10px;
    box-shadow: none;
  }

  :deep(.el-input__inner) {
    --el-input-inner-height: 48px;
  }
  :deep(.el-input-group__append) {
    background: var(--el-color-primary);
    color: #fff;
    padding: 0 10px;
    box-shadow: none;
  }
}

:deep(.el-divider--horizontal) {
  margin: 20px 0 13px 0;
}

.collection-icon {
  width: 24px;
  height: 24px;
}
</style>
